package com.beta.platform.rest.interceptor;

import com.alibaba.fastjson.JSON;
import com.beta.platform.rest.auth.LoginAccountDetail;
import com.beta.platform.rest.auth.LoginAccountSecurity;
import com.beta.platform.rest.constant.RequestHeaderNames;
import com.beta.platform.rest.constant.UserType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.JsonUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * 解析已授权的用户信息
 */
@Slf4j
public class AddLoginAccountInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String userJson = request.getHeader(RequestHeaderNames.JWT_USER.getValue());		
		if (StringUtils.isNotBlank(userJson)) {
			// 常规逻辑，走授权获取到bjwt
			userJson = new String(Base64.getDecoder().decode(userJson), StandardCharsets.UTF_8);
			//兼容 上下游返回的userId格式为corpId/userId
			LoginAccountDetail loginAccountDetail = JSON.parseObject(userJson, LoginAccountDetail.class);
			if(null != loginAccountDetail && null != loginAccountDetail.getThirdUserInfo() && !StringUtils.isEmpty(loginAccountDetail.getThirdUserInfo().getUserId())){
				String userId = loginAccountDetail.getThirdUserInfo().getUserId();
				if(userId.contains("/")){
					loginAccountDetail.getThirdUserInfo().setCorpId(userId.split("/")[0]);
					loginAccountDetail.getThirdUserInfo().setUserId(userId.split("/")[1]);
				}
			}
			LoginAccountSecurity.setLoginAccountDetail(loginAccountDetail);
		} else {
			// 测试场景，适用于swagger或者postman等测试时
			String userId = request.getHeader(RequestHeaderNames.USER_ID.getValue());
			if (StringUtils.isNotBlank(userId)) {
				LoginAccountDetail loginAccountDetail = new LoginAccountDetail();
				loginAccountDetail.setId(userId);
				String aId = request.getHeader(RequestHeaderNames.PARTNER_ID.getValue());
				if (StringUtils.isNotBlank(aId)) {
					loginAccountDetail.setPartnerId(Long.parseLong(aId));
					loginAccountDetail.setUserType(UserType.MEMBER);
				} else {
					loginAccountDetail.setUserType(UserType.USER);
				}
				LoginAccountSecurity.setLoginAccountDetail(loginAccountDetail);
			}
		}
		return super.preHandle(request, response, handler);
	}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginAccountSecurity.clean();
    }

}
